/**
 * Copyright (C) 2012 João Francisco Biondo Trinca
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 *
 * @author     João Francisco Biondo Trinca <wolfulus@gmail.com>
 * @copyright  2012 João Francisco Biondo Trinca <wolfulus@gmail.com>
 * @license    http://www.opensource.org/licenses/mit-license.html  MIT License
 *
 */

/**
 * NetBuffer classes
 */
var Buffer = require('buffer').Buffer;
var NetWriter = require('./netwriter').NetWriter;
var NetReader = require('./netreader').NetReader;

/**
 * Network buffer class
 */
function NetBuffer(size) {

    // Current buffer offset
    this.length = 0;

    // Stores the buffer size
    this.size = size;

    // Stores the contents of the buffer
    this.contents = new Buffer(size);

}

/**
 * Pushes new incoming data to the buffer.
 * @param other Incoming parameters
 */
NetBuffer.prototype.push = function (other) {
    var len = other.length;
    if (this.length + len > this.size) {
        return false;
    }
    other.copy(this.contents, this.length, 0, len);
    this.length += len;
    return true;
};

/**
 * Removes already-processed data from the front of the buffer.
 * @param other Incoming parameters
 */
NetBuffer.prototype.pop = function (bytes) {
    if (bytes > this.length) {
        return false;
    } else if (bytes == this.length) {
        this.length = 0;
        return true;
    } else {
        var temp = this.contents.slice(bytes, this.length);
        for (var i = 0; i < temp.length; i++) {
            this.contents[i] = temp[i];
        }
        this.length -= bytes;
        return true;
    }
};

/**
 * Writer class
 */
exports.NetWriter = NetWriter;

/**
 * Reader class
 */
exports.NetReader = NetReader;

/**
 * Buffer class
 */
exports.NetBuffer = NetBuffer;
